<template>
  <BasicModal
    v-bind="$attrs"
    @ok="handleSubmint"
    :minHeight="20"
    okText="提交"
    @register="register"
    :title="modalTitle"
    :loading="loading"
    :confirmLoading="loading"
    @visible-change="handleVisibleChange"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm" />
    </div>
    <template #centerFooter>
      <a-button type="primary" @click="handleTest" :loading="loading"> 测试链接 </a-button>
    </template>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { BasicModal, useModal } from '/@/components/Modal';
  import { computed, nextTick, toRef, ref } from 'vue';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getDatabaseType } from '/@/api/hda/index';

  import { checkIp, checkName } from '/@/utils/index';
  import {
    adddbconfig,
    updatedbconfig,
    testdbconnection,
    getdatabasetemplates,
  } from '/@/api/resource/index';

  const props = defineProps({
    info: {
      type: Object,
      default: () => {},
    },
  });
  let loading = ref(false);
  // 模板
  let tplList = [];
  let modalTitle = computed(() => {
    return `${props.info.type === 'add' ? '新增' : `编辑（${props.info.data.Name}）`}`;
  });
  // 表单内容
  const schemas: FormSchema[] = [
    {
      field: 'Name',
      component: 'Input',
      label: '名称：',
      componentProps: {
        placeholder: '请输入名称',
      },
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => checkName(value, '名称'),
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'DataType',
      component: 'Select',
      label: '数据库类型：',
      colProps: {
        span: 24,
      },
      componentProps: {
        placeholder: '请选择数据库类型',
        options: [],
        fieldNames: { label: 'Key', value: 'Value', key: 'Key' },
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => {
            if (['', null, undefined].indexOf(value) >= 0) {
              /* eslint-disable-next-line */
              return Promise.reject('请选择数据库类型');
            }
            return Promise.resolve();
          },
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'ServerUrl',
      component: 'Input',
      label: '地址：',
      ifShow: ({ values }) => {
        return setFormItem('ServerUrl', values.DataType);
      },
      componentProps: {
        placeholder: '请输入地址',
      },
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => checkIp(value, '地址'),
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'Port',
      component: 'Input',
      label: '端口：',
      componentProps: {
        placeholder: '请输入端口',
      },
      colProps: {
        span: 24,
      },
      ifShow: ({ values }) => {
        return setFormItem('Port', values.DataType);
      },
      rules: [
        {
          required: true,
          message: '请输入端口',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'UserName',
      component: 'Input',
      label: '账号：',
      componentProps: {
        placeholder: '请输入账号',
      },
      ifShow: ({ values }) => {
        return setFormItem('UserName', values.DataType);
      },
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          message: '请输入账号',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'PassWord',
      component: 'Input',
      label: '密码：',
      componentProps: {
        placeholder: '请输入密码',
      },
      colProps: {
        span: 24,
      },
      ifShow: ({ values }) => {
        return setFormItem('PassWord', values.DataType);
      },
      rules: [
        {
          required: true,
          message: '请输入密码',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'TimeOut',
      component: 'InputNumber',
      label: '过期时间：',
      colProps: {
        span: 24,
      },
      defaultValue: 1,
      componentProps: {
        min: 0,
      },
      rules: [
        {
          required: true,
          message: '请输入过期时间',
          trigger: ['change', 'blur'],
        },
      ],
      suffix: '(分钟)',
    },
    {
      field: 'ConnectString',
      component: 'Input',
      label: '连接字符串：',
      ifShow: ({ values }) => {
        return setFormItem('ConnectString', values.DataType);
      },
      componentProps: {
        placeholder: '请输入连接字符串',
      },
      colProps: {
        span: 24,
      },
    },
  ];

  const [
    registerForm,
    { validateFields, setFieldsValue, resetFields, clearValidate, updateSchema },
  ] = useForm({
    labelWidth: 120,
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  const { createMessage } = useMessage();
  const { t } = useI18n();
  const emit = defineEmits(['submitSuccess']);
  const [register] = useModal();
  async function handleTest() {
    loading.value = true;
    try {
      let res = await validateFields();
      let resByTest = await testdbconnection([res]);
      if (resByTest) {
        createMessage.success('测试链接成功');
      } else {
        createMessage.error('测试链接失败');
      }
      loading.value = false;
    } catch (_e) {
      loading.value = false;
    }
  }
  // 获取数据库类型
  async function getDatabaseTypeFn() {
    loading.value = true;
    try {
      let res = await getDatabaseType();
      nextTick(() => {
        updateSchema({
          field: 'DataType',
          componentProps: {
            options: res || [],
          },
        });
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  // 获取模版
  async function getdatabasetemplatesFn() {
    loading.value = true;
    try {
      let res = await getdatabasetemplates();

      tplList = res;
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }

  async function handleSubmint() {
    try {
      let res = await validateFields();
      if (props.info.data.Name) {
        await updatedbconfig([props.info.data.Name, res]);
      } else {
        await adddbconfig([res]);
      }
      createMessage.success(t('layout.setting.operatingTitle'));
      emit('submitSuccess', {});
    } catch (error: any) {
      console.log('not passing', error);
    }
  }
  function setFormItem(targetForm, DBType) {
    return (
      tplList.filter(
        (item) => item.DBType === DBType && item.TemplateField.indexOf(targetForm) >= 0,
      ).length > 0
    );
  }
  function handleVisibleChange(visible) {
    if (visible) {
      nextTick(async () => {
        await getDatabaseTypeFn();
        await getdatabasetemplatesFn();
        let data: any = toRef(props.info, 'data');
        let setValue: any = data.value;
        setFieldsValue(setValue);

        clearValidate();
      });
    } else {
      resetFields();
    }
  }
</script>

<style lang="less" scoped>
  .slot-select {
    width: 100%;
    height: 32px;
    padding: 0 11px;
    display: flex;
    position: relative;
    background-color: #fff;
    border: 1px solid #d9d9d9;
    border-radius: 2px;
    cursor: pointer;
  }

  .slot-select:hover {
    border: 1px solid #1e80ff;
  }

  .slot-select-con {
    margin-right: 18px;
    line-height: 30px;
    flex: 1;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    color: #000000d9;
    font-size: 14px;
  }

  .con-placeholder {
    color: #bfbfbf;
  }

  .icon-style {
    line-height: 30px;
    font-size: 11px;

    color: #bfbfbf;
  }

  .erro-style {
    border: 1px solid #ed6f6f !important;
  }

  .slot-select-diabled {
    background: #f5f5f5;
    cursor: not-allowed;

    .slot-select-con {
      color: rgba(0, 0, 0, 0.25);
    }
  }

  .slot-select-diabled:hover {
    border: 1px solid #d9d9d9;
  }
</style>
